import { Table } from '../schema/Table';
import { Internal } from './Internal';
import { ColumnType } from '../schema/Column';

export namespace Check {

  /**
   * 检查表是否存在主键
   *
   * @param targetTable 要检查的表
   */
  export function checkTableHasIdColumn(targetTable: Table<any>) {
    const useOptions = targetTable[Internal.TableOptions]
    if (useOptions.idColumns.length === 0) {
      throw new Error(`Table "${targetTable.tableName}" there is no primary key.`)
    }
  }

  /**
   * 检查表是否是多主键
   *
   * @param targetTable 要检查的表
   */
  export function checkTableHasAtMostOneIdColumn(targetTable: Table<any>) {
    checkTableHasIdColumn(targetTable)
    const useOptions = targetTable[Internal.TableOptions]
    if (useOptions.idColumns.length > 1) {
      throw new Error(`Table "${targetTable.tableName}" there is more than one primary key. Only one primary key is allowed.`)
    }
  }

  /**
   * 检查表是否包含某个列
   *
   * @param targetTable 要检查的表
   * @param column 要检查的列
   */
  export function checkTableHasColumn(targetTable: Table<any>, column: ColumnType) {
    const useOptions = targetTable[Internal.TableOptions]
    const hasColumn = useOptions.columns.some(item => Object.is(column, item))
    if (!hasColumn) {
      throw new Error(`Table "${targetTable.tableName}" does not have a column named "${column.fieldName}".`);
    }
  }
}